package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.constants.MQConstants;
import cn.itsource.hrm.domain.Pager;
import cn.itsource.hrm.feignclients.FastdfsFeignClient;
import cn.itsource.hrm.feignclients.RedisFeignClient;
import cn.itsource.hrm.mapper.PagerMapper;
import cn.itsource.hrm.mapper.SiteMapper;
import cn.itsource.hrm.service.IPagerService;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.MyFileUtils;
import cn.itsource.hrm.util.VelocityUtils;
import cn.itsource.hrm.util.ZipUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author luobiao
 * @since 2020-02-26
 */
@Service
public class PagerServiceImpl extends ServiceImpl<PagerMapper, Pager> implements IPagerService {

    @Autowired
    private FastdfsFeignClient fastdfsFeignClient;

    @Autowired
    private RedisFeignClient redisFeignClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SiteMapper siteMapper;

    //获取系统临时目录 ：\Users\ADMINI~1\AppData\Local\Temp\
    private String getTempDir(){
        String tempDir = System.getProperty("java.io.tmpdir");
        return tempDir;
    }

    //页面静态化业务逻辑
    @Override
    public void pageStatic(String pageName, String redisDataKey) throws Exception {
        //1.参数的判断
        if(!StringUtils.hasLength(pageName) || !StringUtils.hasLength(redisDataKey)){
            throw new RuntimeException("页面静态化失败,参数异常");
        }
        //2.准备模板=====================================================
        //2.1通过pageName查询pager对象（获取模板下载地址）
        Pager pager = baseMapper.selectByName(pageName);
        //2.2通过模板下载地址，下载模板
        String templateUrl = pager.getTemplateUrl();
        byte[] templateZipBytes = fastdfsFeignClient.download(templateUrl);
        if(templateZipBytes == null || templateZipBytes.length==0){
            throw new RuntimeException("模板下载失败");
        }
        //2.3解压下载后的模板压缩包zip
        //先将波byte[]写到磁盘,临时目录
        String zipPath = getTempDir()+pageName+".zip";
        //创建文件
        File zipFile = MyFileUtils.createFile(zipPath);
        //把byte[] 下载到磁盘
        FileCopyUtils.copy(templateZipBytes,zipFile);
        //模板的解压路径
        String unZipPath = getTempDir()+"pagestatic/";
        //解压模板压缩文件
        ZipUtils.unZip(zipPath,unZipPath);


        //3.准备填充数据=====================================================
        //3.1根据redisDataKey查询redis中的treeData数据
        AjaxResult ajaxResult = redisFeignClient.get(redisDataKey);
        if(!ajaxResult.isSuccess() || ajaxResult.getResultObj()==null){
            throw new RuntimeException("数据获取失败");
        }
        //将从redis获取到的数据转为map
        String stringData = ajaxResult.getResultObj().toString();
        Map<String,Object> model = JSON.parseObject(stringData, Map.class);
        //3.2 zip的解压路径作为staticroot的参数值
        model.put("staticRoot",unZipPath);

        //4.合并数据和模板=====================================================
        //4.1 通}过模板和数据作为参数，使用模板引擎合并为html
        //解压后模板的真实路径
        String templatePath = unZipPath+pageName+".vm";
        //生成html的临时路径
        String htmlPath = unZipPath+pageName+".html";
        //合并数据和模板，生成html
        VelocityUtils.staticByTemplate(model,templatePath,htmlPath);


        //5.推送html=====================================================
        //5.1 将html上传到fastdfs，拿到上传后的地址
        byte[] htmlBytes = FileCopyUtils.copyToByteArray(new File(htmlPath));
        AjaxResult htmlUploadResult = fastdfsFeignClient.uploadBytes(htmlBytes, "html");
        if (!htmlUploadResult.isSuccess() || htmlUploadResult.getResultObj()==null){
            throw new RuntimeException("文件上传失败");
        }


        //6.发送消息给mq=====================================================
        //6.1 发送的内容：1.html的下载地址2.html存放到nginx的物理路径
        //获取上传成功后，html在fastdfs服务的下载地址
        String htmlPathInFastdfs = htmlUploadResult.getResultObj().toString();
        //Nginx的物理路径
        String physicalPath = pager.getPhysicalPath();
        Map<String,String> mqMessage = new HashMap<>();
        mqMessage.put("htmlPathInFastdfs",htmlPathInFastdfs);
        mqMessage.put("physicalPath",physicalPath);

        //获取routingkey,即获取对应站点的sn
        String routingKey = siteMapper.selectById(pager.getSiteId()).getSn();
        //发送消息 参数交换机，routingkey，消息
        rabbitTemplate.convertAndSend(MQConstants.NAME_EXCHANGE_PAGE_DIRECT,
                routingKey,JSON.toJSONString(mqMessage));

    }
}
